package com.youku.wangheng.utils;


import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;


/**
 * @author william
 *
 */
public class Request{
	
	public static String requestGet(String url){
		return requestGet(url,1000);
	}
	
	public static String requestPost(String url, Map<String, String> params) { 
		return requestPost(url, params, 1000);
	}
	/**
	 * 短链接
	 */
	public static String requestGet(String url,int timeout){
		HttpClient client = new HttpClient();
		String result = null;
		GetMethod method = new GetMethod(url);
		
//		method.setRequestHeader("Accept","*/*");
//		method.setRequestHeader("Connection","close");
//		method.setRequestHeader("Accept-Language","zh-cn");
//		method.setRequestHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//		method.setRequestHeader("Cache-Control","no-cache");
		method.getParams().setSoTimeout(timeout);
	//	method.setFollowRedirects(true);
	//	method.setRequestHeader("Cookie",cookie);
		
		
//		method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		try {
			client.executeMethod(method);
			result = method.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			method.releaseConnection();
		}
		return result;
	}
	
	public static String requestPost(String url, Map<String, String> params, int timeOut) {
		HttpClient client = new HttpClient();
		String result = null ;
		PostMethod postMethod = new PostMethod(url);
		
		for(Entry<String, String> entry : params.entrySet()) {
			postMethod.addParameter(entry.getKey(), entry.getValue());
		}
		
		try {
			client.executeMethod(postMethod);
			result = postMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}
		
		return result;
	}
}
